﻿using System;
using System.Collections;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeSingleTypeCollection(CustomSerializerState state, ICollection collection, Type itemType)
        {
            TypeHandler handler;            
            if (SimpleTypes.TryGetValue(itemType, out handler))
            {
                if (itemType == typeof (byte))
                {
                    byte[] b = new byte[collection.Count];
                    collection.CopyTo(b, 0);
                    SimpleTypes[typeof (byte[])].Write(state, b); // optimized for byte[]
                }
                else
                {
                    var a = Array.CreateInstance(itemType, collection.Count);
                    collection.CopyTo(a, 0);
                    for (var i = 0; i < a.Length; i++)
                        handler.Write(state, a.GetValue(i));
                }
            }
            else
                foreach (var item in collection)
                {
                    if (item == null) state.writeTypeName(null);
                    else
                    {
                        state.writeTypeName(item.GetType());
                        writeValue(state, item, null); // todo check enum[]
                    }
                }
        }

        void readSingleTypeCollection(CustomSerializerState state, IList list, Type storedType, Type ownerType, string propertyName)
        {
            var storeTypeName = storedType.Name;
            TypeHandler handler;
            if (SimpleTypes.TryGetValue(storedType, out handler))
            {
                if (storedType == typeof(byte)) // optimized for byte[]
                {
                    var b = SimpleTypes[typeof (byte[])].Read(state) as byte[];
                    if(b != null)
                        for (var i = 0; i < b.Length; i++) list[i] = b[i];
                }
                else
                    for (var i = 0; i < list.Count; i++) list[i] = handler.Read(state);
            }
            else
                for (var i = 0; i < list.Count; i++)
                {
                    var typeName = state.readTypeName();
                    bool success = false;
                    list[i] = string.IsNullOrEmpty(typeName) ? null : readValue(state, getTypeByName(typeName, state.settings.ClassMap), ownerType, propertyName, out success);
                }
        }
    }
}